package cn.antsing.oauth2login;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.oauth2.client.OidcBackChannelLogoutHandler;
import org.springframework.security.oauth2.client.oidc.session.InMemoryOidcSessionRegistry;
import org.springframework.security.oauth2.client.oidc.web.logout.OidcClientInitiatedLogoutSuccessHandler;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.session.HttpSessionEventPublisher;

@Configuration
@EnableWebSecurity
public class Oauth2LoginConfiguration {

    @Bean
    OidcBackChannelLogoutHandler oidcLogoutHandler() {
        return new OidcBackChannelLogoutHandler(new InMemoryOidcSessionRegistry());
    }

    @Bean
    public HttpSessionEventPublisher sessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http, ClientRegistrationRepository clientRegistrationRepository) throws Exception {
        // 创建基于 OIDC 的退出成功处理器
        OidcClientInitiatedLogoutSuccessHandler oidcLogoutSuccessHandler =
                new OidcClientInitiatedLogoutSuccessHandler(clientRegistrationRepository);
        // 设置注销成功后重定向的地址，默认会跳转到授权服务器的登录页面
        // 这里设置为退出后跳回首页
//        oidcLogoutSuccessHandler.setPostLogoutRedirectUri("/login");
        oidcLogoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}/login");

//        http
//                .authorizeHttpRequests(authz -> authz
//                        .anyRequest().authenticated()
//                )
//                .oauth2Login(Customizer.withDefaults())
////                .logout(logout -> logout
////                                .logoutSuccessHandler(oidcLogoutSuccessHandler) // 关键：使用 OIDC 退出处理器
////                        // .logoutSuccessUrl("/") // 如果不用上面的 Handler，可以用这个简单配置，但无法通知AS
////                        // 其他 logout 配置...
////                );
//                .logout(logout ->
//                        logout.logoutSuccessUrl("/login")           // 退出后跳转的页面
//                        .clearAuthentication(true)       // 清除认证信息
//                        .invalidateHttpSession(true)     // 使 session 失效
//                        .deleteCookies("JSESSIONID")     // 删除 cookie（可选）
//                        .logoutSuccessHandler(oidcLogoutSuccessHandler) // 关键：使用 OIDC 退出处理器
//                );


        http.authorizeHttpRequests(auth->{
                    auth.requestMatchers(HttpMethod.GET, "/login","/logout").permitAll()
                            .anyRequest().authenticated();
                }).oauth2Client(Customizer.withDefaults())
                .oauth2Login(Customizer.withDefaults())
                .oidcLogout((logout) -> logout
                        .backChannel(Customizer.withDefaults())
                )
                .logout(logout -> logout
                        .logoutSuccessHandler(oidcLogoutSuccessHandler)
                );

        return http.build();


    }
}
